package users

import (
	"fmt"
	"gitee.com/ha666/golibs"
	"github.com/astaxie/beego/logs"
	"ha666web/controllers"
	"ha666web/models"
	"time"
)

type LoginUserController struct {
	controllers.LimitingController
}

func (this *LoginUserController) Get() {
	this.DelSession("user_login")
	//限制登录页每10分钟只只能访问10次
	{
		key := fmt.Sprintf("fc_get_%s_%d", this.Ctx.Input.IP(), golibs.Unix()/600)
		beyond, errmsg := this.Limiting("get", key, 600)
		if beyond {
			ipblacklist := &models.Ipblacklist{
				IP:       this.Ctx.Input.IP(),
				Status:   1,
				ExpireIn: golibs.Unix() + 86400,
			}
			issuccess, err := models.InsertUpdateIpblacklist(*ipblacklist)
			if err != nil {
				logs.Error("【Get】IP:%s,写入黑名单出错:%s", ipblacklist.IP, err.Error())
			} else {
				if !issuccess {
					logs.Error("【Get】IP:%s,写入黑名单失败", ipblacklist.IP)
				} else {
					logs.Info("【Get】IP:%s,写入黑名单成功")
				}
			}
			this.CustomAbort(403, "10分钟内get请求超频,"+errmsg)
			return
		}
	}
	this.TplName = "users/login.tpl"
}

func (this *LoginUserController) Post() {
	defer func() {
		if err := recover(); err != nil {
			this.Data["json"] = map[string]interface{}{"code": 0, "message": fmt.Sprintf("异常:%v", err)}
			this.ServeJSON()
			return
		}
	}()
	//限制每IP每天登录次数
	{
		key := fmt.Sprintf("fc_login_%s_%s", this.Ctx.Input.IP(), time.Now().Format(golibs.Time_TIMEyyyyMMdd))
		beyond, errmsg := this.Limiting("post", key, 10)
		time.Sleep(3 * time.Second)
		if beyond {
			this.Data["json"] = map[string]interface{}{"code": 0, "message": "今天登录已达到上限," + errmsg}
			this.ServeJSON()
			return
		}
	}
	email := this.GetString("email")
	password := this.GetString("password")
	if len(email) < 5 {
		this.Data["json"] = map[string]interface{}{"code": 0, "message": "请填写邮箱地址"}
		this.ServeJSON()
		return
	}
	if !golibs.IsEmail(email) {
		this.Data["json"] = map[string]interface{}{"code": 0, "message": "邮箱地址格式错误"}
		this.ServeJSON()
		return
	}
	if len(password) < 8 {
		this.Data["json"] = map[string]interface{}{"code": 0, "message": "请填写密码"}
		this.ServeJSON()
		return
	}
	if !golibs.IsLetterOrNumber(password) {
		this.Data["json"] = map[string]interface{}{"code": 0, "message": "密码格式错误"}
		this.ServeJSON()
		return
	}
	userinfo, err := models.GetUserinfoByEmail(email)
	if err != nil {
		this.Data["json"] = map[string]interface{}{"code": 0, "message": "登录失败:" + err.Error()}
		this.ServeJSON()
		return
	}
	if userinfo.UserId <= 0 {
		this.Data["json"] = map[string]interface{}{"code": 0, "message": "用户不存在"}
		this.ServeJSON()
		return
	}
	if len(userinfo.Password) != 128 {
		this.Data["json"] = map[string]interface{}{"code": 0, "message": "密码怎么是空的呢"}
		this.ServeJSON()
		return
	}
	if len(userinfo.Slat) != 32 {
		this.Data["json"] = map[string]interface{}{"code": 0, "message": "盐呢"}
		this.ServeJSON()
		return
	}
	if fmt.Sprintf("%x", golibs.HmacSha512([]byte(password), []byte(userinfo.Slat))) != userinfo.Password {
		this.Data["json"] = map[string]interface{}{"code": 0, "message": "密码错误"}
		this.ServeJSON()
		return
	}
	if userinfo.Status == 1 {
		this.Data["json"] = map[string]interface{}{"code": 0, "message": "帐号被禁用"}
		this.ServeJSON()
		return
	}
	userinfo.LastLoginIP = this.Ctx.Input.IP()
	userinfo.LoginTime = golibs.Unix()
	logininfo := &models.Logininfo{
		UserId:    userinfo.UserId,
		SourceId:  1,
		AppKey:    0,
		BuildPath: "/",
		IP:        this.Ctx.Input.IP(),
		UserAgent: this.Ctx.Input.UserAgent(),
		LoginTime: golibs.Unix(),
	}
	issuccess, errmsg := models.InsertLoginInfoByTrans(userinfo, *logininfo)
	if !issuccess {
		this.Data["json"] = map[string]interface{}{"code": 0, "message": "登录失败:" + errmsg}
		this.ServeJSON()
		return
	}
	this.SetSession("user_login", fmt.Sprintf("%d||%s||%s", userinfo.UserId, userinfo.UserNick, userinfo.Email))
	this.Data["json"] = map[string]interface{}{"code": 1, "message": "恭喜你，登录成功"}
	this.ServeJSON()
}
